package userlogic

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/tool"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type GoogleAuthenticationAdminLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoogleAuthenticationAdminLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoogleAuthenticationAdminLogic {
	return &GoogleAuthenticationAdminLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoogleAuthenticationAdminLogic) GoogleAuthenticationAdmin(in *login_rpc.GoogleAuthenticationAdminRequest) (*login_rpc.GoogleAuthenticationAdminResponse, error) {
	var commonResp login_rpc.CommonResp
	if in.Account == "" {
		commonResp.Code = config.ParameterError
		commonResp.Message = "wrong parameters"
		return &login_rpc.GoogleAuthenticationAdminResponse{CommonResp: &commonResp}, nil
	}
	adminUser, err := model.NewAdminUserModel(l.ctx, l.svcCtx.Db).GetAdminUserByAccount(in.Account)

	if err != nil {
		commonResp.Code = config.DBError
		commonResp.Message = "query failed"
		return &login_rpc.GoogleAuthenticationAdminResponse{CommonResp: &commonResp}, nil
	}

	if adminUser.Id == 0 {
		commonResp.Code = config.ParameterError
		commonResp.Message = "no such account"
		return &login_rpc.GoogleAuthenticationAdminResponse{CommonResp: &commonResp}, nil
	}

	// 如果用户开启了谷歌登录，但没有谷歌二维码，则生成二维码 tody
	if adminUser.IsOpenGoogle == 1 {
		if adminUser.GoogleCode == "" {
			adminUser.GoogleCode, err = tool.GenGoogleAuthSecret()
			if err != nil {
				commonResp.Code = config.TokenError
				commonResp.Message = "failed to generate google auth secret"
				logc.Error(l.ctx, "GoogleAuthenticationAdmin-GenGoogleAuthSecret,err:", err)
				return &login_rpc.GoogleAuthenticationAdminResponse{CommonResp: &commonResp}, nil
			}

			// 更新到数据库
			err := model.NewAdminUserModel(l.ctx, l.svcCtx.Db).UpdateUserGoogleCode(adminUser.Id, adminUser.GoogleCode)
			if err != nil {
				commonResp.Code = config.TokenError
				commonResp.Message = "update failed"
				return &login_rpc.GoogleAuthenticationAdminResponse{CommonResp: &commonResp}, nil
			}
		}

		// 通过密钥生成二维码
		adminUser.GoogleCode = tool.BuildGoogleQR(adminUser.GoogleCode)
	}

	return &login_rpc.GoogleAuthenticationAdminResponse{CommonResp: &commonResp, IsBinding: adminUser.IsBindingGoogle, IsOpen: adminUser.IsOpenGoogle, QrCode: adminUser.GoogleCode}, nil
}
